//
//  VKCertificateController.m
//  V-Learn
//
//  Created by liubo on 2019/1/2.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKCertificateController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
@interface VKCertificateController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger tagIndex;
@property (nonatomic, strong) NSData *data1;
@property (nonatomic, strong) NSData *data2;

@end

@implementation VKCertificateController
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = @[];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"实名认证";
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];

    [self setupLoadFirstData];
}
- (void)setupCommit{
    // 实名认证信息已提交
    UIImageView *cerImageV = [[UIImageView alloc]init];
    [self.view addSubview:cerImageV];
    cerImageV.image = [UIImage imageNamed:@"success"];
    [cerImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(130);
        make.height.equalTo(@110);
        make.width.equalTo(@140);
    }];

    UILabel *cerLabel = [[UILabel alloc]init];
    [self.view addSubview:cerLabel];
    cerLabel.text = @"您的实名认证信息已提交";
    cerLabel.font = [UIFont systemFontOfSize:16];
    cerLabel.textAlignment = NSTextAlignmentCenter;
    cerLabel.textColor = [UIColor cz_colorWithRed:237 green:100 blue:52];
    [cerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(cerImageV.mas_bottom).offset(20);
        make.left.right.mas_equalTo(self.view);
    }];
}

- (void)setupLoadFirstData{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    VKWeakSelf(self)
    NSMutableDictionary *pagramsD = @{@"token":[UserModel getUserModel].token}.mutableCopy;
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKMeQueryAuth withPostParams:pagramsD withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            if ([result[@"data"] isEqual:[NSNull null]]) {
                [self setupUI];
            }else{
                [self setupCommit];
            }
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
    }];
    
}
- (void)setupUI{
    
    UIView *lineView = [[UIView alloc]init];
    [self.view addSubview:lineView];
    lineView.backgroundColor = [UIColor cz_colorWithRed:244 green:244 blue:244];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@1);
        make.left.right.top.equalTo(self.view);
    }];
    
    _scrollView = [[UIScrollView alloc]init];
    [self.view addSubview:_scrollView];
//    _scrollView.backgroundColor = [UIColor redColor];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(lineView.mas_bottom);
        make.height.equalTo(@([UIScreen cz_screenWidth] - LBNAVBAR_HEIGHT));
    }];
    
    UIImageView *faceImageV = [[UIImageView alloc]init];
    [_scrollView addSubview:faceImageV];
    faceImageV.image = [UIImage imageNamed:@"shenfenzhengzhengmian"];
    faceImageV.tag = 100;
    faceImageV.layer.cornerRadius = 10;
    faceImageV.layer.masksToBounds = YES;
    faceImageV.contentMode = UIViewContentModeScaleAspectFill;
    // 超出边框的内容都剪掉
    faceImageV.clipsToBounds = YES;
    [faceImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@290);
        make.top.mas_equalTo(_scrollView).offset(24);
        make.left.mas_equalTo(([UIScreen cz_screenWidth] - 290) / 2.0);
        make.height.equalTo(@184);
    }];

    UIButton *faceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scrollView addSubview:faceBtn];
    faceBtn.tag = 200;
    faceBtn.backgroundColor = [UIColor clearColor];
    [faceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(faceImageV);
    }];
    [faceBtn addTarget:self action:@selector(uploadClick:) forControlEvents:UIControlEventTouchUpInside];


    UILabel *faceLabel = [[UILabel alloc]init];
    [_scrollView addSubview:faceLabel];
    faceLabel.text = @"请上传身份证正面照";
    faceLabel.textAlignment = NSTextAlignmentCenter;
    faceLabel.textColor = [UIColor cz_colorWithRed:52 green:52 blue:52];
    [faceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(faceBtn.mas_bottom).offset(12);
        make.left.right.mas_equalTo(self.view);
    }];
    
    UIImageView *oppositeImageV = [[UIImageView alloc]init];
    [_scrollView addSubview:oppositeImageV];
    oppositeImageV.image = [UIImage imageNamed:@"shenfenzhengfanmian"];
    oppositeImageV.layer.cornerRadius = 10;
    oppositeImageV.layer.masksToBounds = YES;
    oppositeImageV.tag = 101;
    oppositeImageV.contentMode = UIViewContentModeScaleAspectFill;
    // 超出边框的内容都剪掉
    oppositeImageV.clipsToBounds = YES;
    [oppositeImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@290);
        make.top.mas_equalTo(faceLabel.mas_bottom).offset(30);
        make.left.mas_equalTo(([UIScreen cz_screenWidth] - 290) / 2.0);
        make.height.equalTo(@184);
    }];
    
    
    UIButton *oppositeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scrollView addSubview:oppositeBtn];
    oppositeBtn.imageView.contentMode = UIViewContentModeScaleAspectFill;
    oppositeBtn.tag = 201;
    [oppositeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(oppositeImageV);
    }];
    [oppositeBtn addTarget:self action:@selector(uploadClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *oppositeLabel = [[UILabel alloc]init];
    [_scrollView addSubview:oppositeLabel];
    oppositeLabel.text = @"请上传身份证反面照";
    oppositeLabel.textAlignment = NSTextAlignmentCenter;
    oppositeLabel.textColor = [UIColor cz_colorWithRed:52 green:52 blue:52];
    [oppositeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(oppositeBtn.mas_bottom).offset(12);
        make.left.right.mas_equalTo(self.view);
    }];
    
    
//    UIButton *commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_scrollView addSubview:commitBtn];
//    commitBtn.backgroundColor = [UIColor cz_colorWithRed:235 green:81 blue:32];
//    [commitBtn setTitle:@"提交认证" forState:UIControlStateNormal];
//    commitBtn.layer.cornerRadius = 23;
//    commitBtn.layer.masksToBounds = YES;
//    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.mas_equalTo([UIScreen cz_screenWidth] - 30);
//        make.top.mas_equalTo(oppositeLabel.mas_bottom).offset(50);
//        make.left.mas_equalTo(15);
//        make.height.equalTo(@46);
//    }];
//    [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
//
    UIButton *commitBtn = [[UIButton alloc]init];
    [_scrollView addSubview:commitBtn];
    [commitBtn setImage:[UIImage imageNamed:@"vkbtn"] forState:UIControlStateNormal];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(oppositeLabel.mas_bottom).offset(50);
        make.left.equalTo(@15);
        make.width.equalTo(@([UIScreen cz_screenWidth] - 30));
        make.height.equalTo(@55);
    }];
    commitBtn.imageView.contentMode = UIViewContentModeScaleToFill;
    [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *commitLabel = [[UILabel alloc]init];
    [_scrollView addSubview:commitLabel];
    commitLabel.textColor = [UIColor whiteColor];
    commitLabel.font = [UIFont systemFontOfSize:16];
    commitLabel.text = @"提交认证";
    [commitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(commitBtn).offset(15);
        make.centerX.equalTo(commitBtn);
    }];
    
    
    [self.view layoutIfNeeded];
    _scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(commitBtn.frame) + 45);
}
// 提交
- (void)commitBtnClick{
    
    if (!_data1) {
        [MBProgressHUD showSuccess:@"请上传身份证正面照" toView:self.view];
        return;
    }
    if (!_data2) {
        [MBProgressHUD showSuccess:@"请上传身份证反面照" toView:self.view];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];

    NSMutableDictionary *pagramsD = @{@"token":[UserModel getUserModel].token}.mutableCopy;
    [WYHXNetWorkService uploadSinglePhotoWith:WKMeAuth params:pagramsD WithDataArray:@[_data1,_data2].mutableCopy withParamsArray:@[@"frontImg",@"reverseImg"].mutableCopy AndFinish:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            [MBProgressHUD showSuccess:@"提交成功" toView:self.view];
            [_scrollView removeFromSuperview];
            [self setupCommit];
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
    }];
    
}
// 正面、反面
- (void)uploadClick:(UIButton *)sender{
    self.tagIndex = sender.tag;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册选择", nil];
    [actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
            case 0:{
                
                NSString * mediaType = AVMediaTypeVideo;
                AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
                if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied ) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"未开启摄像头功能" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去开启", nil];
                    alert.tag = 11;
                    [alert show];
                }else{
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                        UIImagePickerController* imagePick = [[UIImagePickerController alloc]init];
                        imagePick.delegate = self;
                        imagePick.allowsEditing = YES;
                        imagePick.sourceType = UIImagePickerControllerSourceTypeCamera;
                        //关键方法
                        dispatch_async(dispatch_get_main_queue(), ^ {
                            [self presentViewController:imagePick animated:YES completion:nil];
                        });
                    }else{
                        [MBProgressHUD showSuccess:@"相机不可用，请检测相机设备" toView:self.view];
//                        [ShowMessage showTextOnly: messageView:[UIApplication sharedApplication].keyWindow];
                    }
                }
                
            }
            break;
            case 1:{
//                NSLog(@"从相册选择");
                UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
                if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                    pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    pickerImage.navigationBar.translucent = NO;
                    pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
                    pickerImage.delegate = self;
                    pickerImage.allowsEditing = YES;
                    [self presentViewController:pickerImage animated:YES completion:nil];
                }else{
                    [MBProgressHUD showSuccess:@"相册不可用，请检测手机相册" toView:self.view];

//                    [ShowMessage showTextOnly:@"相册不可用，请检测手机相册" messageView:[UIApplication sharedApplication].keyWindow];
                }
                
            }
            break;
            case 2:
            
            break;
            
        default:
            break;
    }
}
#pragma mark---是否开启摄像头
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
            case 0:
            return;
            break;
            case 1:
        {
            if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
                NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if([[UIApplication sharedApplication] canOpenURL:url]) {
                    NSURL *url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    [[UIApplication sharedApplication] openURL:url];
                }
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"您没有开启对本应用的相机功能，请开启相机使用权限:设置 > 隐私 > 相机 > 海啸游戏应用，并重新开启本应用！" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
                [alert show];
            }
        }
            break;
            
        default:
            break;
    }
}

#pragma mark---从相册选取
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        [picker dismissViewControllerAnimated:YES completion:^{

            if ([info[@"UIImagePickerControllerMediaType"] isEqualToString:@"public.movie"]) {
                [MBProgressHUD showSuccess:@"不能选择视频" toView:self.view];
                return ;
            }
            UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
            image = [self imageCompressForWidth:image targetWidth:300];
            NSData *data = UIImageJPEGRepresentation(image, 0.5);
            if (self.tagIndex == 200) {
                UIImageView *imageV = [self.view viewWithTag:100];
                imageV.image = image;
                _data1 = data;
            }else if (self.tagIndex == 201){
                UIImageView *imageV = [self.view viewWithTag:101];
                imageV.image = image;
                _data2 = data;
            }
//            weak_imageView.image = image;
//            weakself.data = data;
            
        }];
        
    }else if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        
        UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
        image = [self imageCompressForWidth:image targetWidth:200];
//        weak_imageView.image = image;
        
        //上传图片
        NSData *imgData = UIImageJPEGRepresentation(image, 0.5);
//        weakself.data = imgData;
        if (self.tagIndex == 200) {
            UIImageView *imageV = [self.view viewWithTag:100];
            imageV.image = image;
            _data1 = imgData;

        }else if (self.tagIndex == 201){
            UIImageView *imageV = [self.view viewWithTag:101];
            imageV.image = image;
            _data2 = imgData;
        }
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//处理图片
-(UIImage *)imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
//设置状态栏颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
//}
//- (void)viewWillDisappear:(BOOL)animated{
//    [super viewWillDisappear:animated];
//    [self setStatusBarBackgroundColor:[UIColor clearColor]];
//}
@end
